<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeFn"
        />
        <el-tree
          :data="depts"
          :props="defaultProps"
          highlight-current
          default-expand-all
          node-key="id"
          :current-node-key="1"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        />
      </div>
      <div v-loading="loading" class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <el-table
          :data="tableData"
          style="width: 100%"
        >
          <el-table-column
            prop="staffPhoto"
            label="头像"
            align="center"
          >
            <template v-slot="{row:{staffPhoto,username}}">
              <el-avatar v-if="staffPhoto" :size="30" :src="staffPhoto" />
              <span v-else class="username">{{ username[0] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="username"
            label="姓名"
          />
          <el-table-column
            sortable
            prop="mobile"
            label="手机号"
          />
          <el-table-column
            sortable
            prop="workNumber"
            label="工号"
          />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
          >
            <template v-slot="{row}">
              {{ employmentType[row.formOfEmployment] || '无' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="departmentName"
            label="部门"
          />
          <el-table-column
            sortable
            prop="timeOfEntry"
            label="入职时间"
          />
          <el-table-column
            label="操作"
            width="200px"
          >
            <template v-slot="{ row }">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="assignRole(row.id)">角色</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="delConfirm(row.id)"
              >
                <template #reference>
                  <el-button type="text" size="mini">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" align="middle" style="height:60px">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :page-size="queryParams.pagesize"
            :current-page.sync="queryParams.page"
            @current-change="getEmployeeList"
          />
        </el-row>
      </div>
    </div>
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" />
    <el-dialog :visible.sync="roleDialog" title="分配角色">
      <el-checkbox-group v-model="checkRoleList">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-row type="flex" justify="center">
          <el-button type="primary" size="mini" @click="confirmRole">确定</el-button>
          <el-button size="mini" @click="assignRoleClose">取消</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartment } from '@/api/department'
import { transListToTree, debounce } from '@/utils'
import { getEmployeeList, getEmployeeExport, delEmployee, getEnableRoleList, getEmployeeDetail, assignRole } from '@/api/employee'
import FileSaver from 'file-saver'
import ImportExcel from './components/ImportExcel.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      showExcelDialog: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      depts: [],
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: null
      },
      tableData: [],
      total: 0,
      employmentType: {
        '1': '正式',
        '2': '非正式'
      },
      roleList: [],
      roleDialog: false,
      checkRoleList: [],
      loading: false,
      currentId: 0
    }
  },
  created() {
    this.getDepartmentList()
    this.getEnableRoleList()
  },
  methods: {
    async confirmRole() {
      await assignRole({ id: this.currentId, roleIds: [...this.checkRoleList] })
      this.$message.success('分配用户角色成功')
      this.assignRoleClose()
    },
    async assignRole(id) {
      this.loading = true
      try {
        const { roleIds } = await getEmployeeDetail(id)
        this.checkRoleList = roleIds
        this.roleDialog = true
        this.currentId = id
      } finally {
        this.loading = false
      }
    },
    assignRoleClose() {
      this.roleDialog = false
    },
    async getEnableRoleList() {
      this.roleList = await getEnableRoleList()
    },
    async delConfirm(id) {
      await delEmployee(id)
      this.$message.success('删除成功')
      if (this.tableData.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.getEmployeeList()
    },
    async exportEmployee() {
      const res = await getEmployeeExport()
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    changeFn: debounce(function() {
      this.queryParams.page = 1
      this.getEmployeeList()
    }),
    // changeFn() {
    //   clearTimeout(this.timer)
    //   this.timer = setTimeout(() => {
    //     this.queryParams.page = 1
    //     this.getEmployeeList()
    //   }, 500)
    // },
    handleNodeClick(current) {
      this.queryParams.departmentId = current.id
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    async getDepartmentList() {
      const res = await getDepartment()
      this.queryParams.departmentId = res[0].id
      this.depts = transListToTree(res, 0)
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList({ ...this.queryParams })
      this.tableData = rows
      this.total = total
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
